package com.example.etwzgzxt.view.fragment;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.example.etwzgzxt.R;
import com.example.etwzgzxt.adapter.SosListAdapter;
import com.example.etwzgzxt.bean.SosInfo;
import com.example.etwzgzxt.tool.HttpHelper;
import com.example.etwzgzxt.tool.InfoApplication;
import com.example.etwzgzxt.tool.tool;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import cz.msebera.android.httpclient.NameValuePair;
import cz.msebera.android.httpclient.message.BasicNameValuePair;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the

 * to handle interaction events.
 * Use the {@link SOSFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class SOSFragment extends Fragment  implements View.OnClickListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private static final String type = "nosos";


    private MapView mMapView = null;
    private BaiduMap mBaiduMap;
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
     private ListView lvsos;
    SosListAdapter adapter;
    List<SosInfo> items = new ArrayList<>();

    Timer timer=null;
    RoutePlanSearch routePlanSearch=null;
    public SOSFragment() {

}
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);


        if(!hidden) {
            timer = new Timer();
            timer.schedule(new Work(),0, 20000);

        }
        else
        if(timer!=null)
            timer.cancel();

    }

    public static SOSFragment newInstance(String param1, String param2) {
        SOSFragment fragment = new SOSFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v=inflater.inflate(R.layout.fragment_sos, container, false);

        lvsos = (ListView)v. findViewById(R.id.lvsos);
        adapter = new SosListAdapter(getActivity(), items);
        lvsos.setAdapter(adapter);
        return v;
    }

    public class BackgroundTask extends AsyncTask<Void, Void, String> {




        @Override
        protected String doInBackground(Void... params) {

               return   handler();

        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            parseResult(result);
        }
    }
    public String handler() {

        String baseURL =    ((InfoApplication)getActivity().getApplicationContext()).getBasehost()+"/sos/getsosdetail.do";
        List<NameValuePair> pair = new ArrayList<>();
        pair.add( new BasicNameValuePair("access_token", ((InfoApplication) getActivity().getApplication()).getAccess_token()));
        for (NameValuePair pairs: pair) {
            System.out.println(pairs.getName()+" "+pairs.getValue());
        }
        return new HttpHelper().post(baseURL, pair);
    }



    public void parseResult(String result) {
        try {
            JSONObject jsonObject = new JSONObject(result);
            switch (jsonObject.getInt("code")) {
                 case 200:
                                  try {

                                      JSONArray jsonArray = new JSONArray(jsonObject.getString("result"));
                                      if(jsonArray!=null) {
                                          int length = jsonArray.length();
                                          items.clear();
                                          for (int i = 0; i < length; i++) {
                                              jsonObject = jsonArray.getJSONObject(i);
                                              items.add(new SosInfo(jsonObject.optString("sosiid"), jsonObject.optString("happendtime"),jsonObject.optString("latitude"), jsonObject.optString("longtitude")
                                              , jsonObject.getJSONObject("device").getString("devicecode")));
                                          }
                                          for (SosInfo item : items) {
                                              System.out.println(item.toString());
                                          }
                                          adapter.updateData(items);
                                      }
                                      else
                                          Toast.makeText(getActivity(),"没有信息",Toast.LENGTH_SHORT).show();
                                  } catch (Exception e) {
                                      e.printStackTrace();
                                  }


                    break;
                case 403:
                    Toast.makeText(getActivity(), "Not Acceptable", Toast.LENGTH_SHORT).show();
                    break;
                case 406:
                    Toast.makeText(getActivity(), "Forbidden", Toast.LENGTH_SHORT).show();
                    break;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (result == null) {
            Toast.makeText(getActivity(), "请检查网络设置", Toast.LENGTH_SHORT).show();
            return;
        }

    }
    class Work extends TimerTask {

        @Override
        public void run() {
            if ( tool.isNetworkAvailable(getActivity().getApplicationContext())) {
                new BackgroundTask().execute();
            }
        }

    }

    JSONObject sos=null,device=null,role=null;
    @Override
    public void onClick(View v) {
        switch (v.getId())
        {

        }
    }



}
